import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  getUserInfo,
  LoginData,
} from '@/api/user';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';
import usePrjPermissionStore from '../project-permission';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: undefined,
    username: undefined,
    name: undefined,
    phone: undefined,
    email: undefined,
    accountState: undefined,
    avatarToken: undefined,
    fid: undefined,
    admin: -1,
    role: '',
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const userName = localStorage.getItem('username') || '';
      const res = await getUserInfo(userName);
      const { name, email, id, accountState, avatarToken, phone, username } =
        res.data;
      let { admin } = res.data;
      admin = admin || 0;
      const role = admin !== -1 ? 'admin' : 'user';
      this.setInfo({
        name,
        email,
        admin,
        id,
        accountState,
        avatarToken,
        phone,
        username,
        role,
      });
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        // @ts-ignore
        setToken(res.access_token);
        // 保存用户名
        localStorage.setItem('username', loginForm.username);
        await this.info();
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      localStorage.removeItem('username');
      removeRouteListener();
      appStore.clearServerMenu();
      const prjPermissionStore = usePrjPermissionStore();
      prjPermissionStore.resetInfo();
    },
    // Logout
    async logout(isRquestLogout = true) {
      try {
        if (isRquestLogout) {
          await userLogout();
        }
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
